package com.alibaba.japan.club.runtime.springmvc.servlet.context;

import javax.servlet.http.HttpServletResponse;

import org.springframework.core.NamedInheritableThreadLocal;
import org.springframework.core.NamedThreadLocal;

/**
 * 保存当前会话的response
 * 
 * @author:shaochuan.wangsc
 * @date:2009-3-31
 * 
 */
public abstract class ResponseContextHolder {

	@SuppressWarnings("unchecked")
	private static final ThreadLocal responseHolder = new NamedThreadLocal("Response");

	@SuppressWarnings("unchecked")
	private static final ThreadLocal inheritableResponseHolder = new NamedInheritableThreadLocal("Response context");

	/**
	 * Reset the response for the current thread.
	 */
	@SuppressWarnings("unchecked")
	public static void resetResponse() {
		responseHolder.set(null);
		inheritableResponseHolder.set(null);
	}

	/**
	 * Bind the given Response to the current thread, <br>
	 * <i>not</i> exposing it as inheritable for child threads.
	 * 
	 * @param the Response to expose
	 * @see #setResponse(HttpServletResponse, boolean)
	 */
	public static void setResponse(HttpServletResponse response) {
		setResponse(response, false);
	}

	/**
	 * Bind the given Response to the current thread.
	 * 
	 * @param the Response to expose
	 * @param inheritable whether to expose the Response as inheritable for child threads (using an
	 *            {@link java.lang.InheritableThreadLocal})
	 */
	@SuppressWarnings("unchecked")
	public static void setResponse(HttpServletResponse response, boolean inheritable) {
		if (inheritable) {
			inheritableResponseHolder.set(response);
			responseHolder.set(null);
		} else {
			responseHolder.set(response);
			inheritableResponseHolder.set(null);
		}
	}

	/**
	 * Return the RequestAttributes currently bound to the thread.
	 * 
	 * @return the RequestAttributes currently bound to the thread, or <code>null</code> if none bound
	 */
	public static HttpServletResponse getResponse() {
		HttpServletResponse response = (HttpServletResponse) responseHolder.get();
		if (response == null) {
			response = (HttpServletResponse) inheritableResponseHolder.get();
		}
		return response;
	}
}
